package Waya::Coordinate;

use warnings;
use strict;

use base 'Waya::Base';

use overload
    '""'  => 'stringify',
    'cmp' => 'str_cmp';

__PACKAGE__->mk_scalar_accessors(qw(x y));


# accept something like 'ac' and set x=1, y=3
sub set_sgf_coordinate {
    my ($self, $coord) = @_;
    my ($x, $y) = map { ord($_)-96 } split // => lc($coord);
    $self->x($x);
    $self->y($y);
}


sub new_from_sgf_coordinate {
    my ($class, $coord) = @_;
    my $self = $class->new;
    $self->set_sgf_coordinate($coord);
    $self;
}


sub to_sgf {
    my $self = shift;
    join '' => map { chr($_+96) } $self->x, $self->y;
}


sub as_list {
    my $self = shift;
    sprintf '(%d,%d)', $self->x, $self->y;
}


sub stringify {
    my $self = shift;
    $self->to_sgf;
}


sub str_cmp {
    my ($lhs, $rhs, $reversed) = @_;
    $_ = "$_" for $lhs, $rhs;
    ($lhs, $rhs) = ($rhs, $lhs) if $reversed;
    $lhs cmp $rhs;
}


sub translate {
    my ($self, $dx, $dy) = @_;
    $self->x($self->x + $dx);
    $self->y($self->y + $dy);
}


1;
